package com.sicau.basedemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sicau.basedemo.config.dozer.DozerUtils;
import com.sicau.basedemo.entity.param.news.NewsAddParam;
import com.sicau.basedemo.entity.param.news.NewsQueryParam;
import com.sicau.basedemo.entity.param.news.NewsUpdateParam;
import com.sicau.basedemo.entity.po.News;
import com.sicau.basedemo.entity.vo.practicenews.PracticeNewsVO;
import com.sicau.basedemo.mapper.NewsMapper;
import com.sicau.basedemo.mapper.VOMapper;
import com.sicau.basedemo.service.NewsService;
import com.sicau.basedemo.util.FileUtil;
import com.sicau.basedemo.util.UserContext;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 新闻稿表 服务实现类
 * </p>
 *
 * @author sxt && ttxxi
 * @since 2021-04-26
 */
@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {

    @Resource
    private DozerUtils dozerUtils;
    @Resource
    NewsMapper newsMapper;
    @Resource
    VOMapper.PracticeNewsVOMapper practiceNewsVOMapper;

    @Override
    public void add(NewsAddParam newsAddParam) {

        News news = dozerUtils.map(newsAddParam, News.class);
        news.setCover(newsAddParam.getCover());
        news.setCreatorId(UserContext.get().getId());
        news.setCreatedTime(LocalDateTime.now());
        newsMapper.insert(news);
    }

    @Override
    public String uploadFile(MultipartFile file) {
        return FileUtil.writeFileToLocal(file);
    }

    @Override
    public void update(NewsUpdateParam param) {
        News news = newsMapper.selectById(param.getId());

        news.setContent(param.getContent());
        news.setTitle(param.getTitle());

        newsMapper.updateById(news);

    }

    @Override
    public IPage<PracticeNewsVO> queryPage(NewsQueryParam param) {
        Page<PracticeNewsVO> page = new Page<>(param.getCurrentPage(), param.getPageSize());
        LambdaQueryWrapper<PracticeNewsVO> queryWrapper = new LambdaQueryWrapper<PracticeNewsVO>()
                .eq(!ObjectUtils.isEmpty(param.getState()), PracticeNewsVO::getState, param.getState())
                .like(!ObjectUtils.isEmpty(param.getTitle()), PracticeNewsVO::getTitle, param.getTitle())
                .like(!ObjectUtils.isEmpty(param.getCreatorName()), PracticeNewsVO::getCreatorName, param.getCreatorName())
                .orderByDesc(PracticeNewsVO::getId);
        return practiceNewsVOMapper.selectPage(page, queryWrapper);
    }

    @Override
    public PracticeNewsVO queryVOById(Integer id) {
        return practiceNewsVOMapper.selectById(id);
    }
}
